package com.design.movieticket.login.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWTUtil;
import com.design.movieticket.common.base.constant.Result;
import com.design.movieticket.common.base.constant.ResultStatus;

import com.design.movieticket.common.util.JwtUtils;
import com.design.movieticket.entity.Balance;
import com.design.movieticket.entity.User;
import com.design.movieticket.entity.UserRole;
import com.design.movieticket.login.entity.LoginUser;
import com.design.movieticket.mapper.BalanceMapper;
import com.design.movieticket.mapper.UserRoleMapper;
import com.design.movieticket.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class LoginService {

    @Resource
    AuthenticationManager authenticationManager;

    @Resource
    RedisService redisService;

    @Resource
    private UserService userService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private BalanceMapper balanceMapper;


    public Result login(User user){
        //先得到前端传入的账号密码Authentication对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        log.info("username为" + user.getUsername() + ",password为" + user.getPassword() + ",authentication为" + authenticationToken);
        //AuthenticationManager authentication进行用户验证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);
        System.out.println("authentication:" + authentication);

        //认证不成功则给出提示
        if (Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }
        //认证成功生成jwt,jet存入Result中,返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        System.out.println("loginService中的loginUser:" + loginUser);
        String id = loginUser.getUser().getId().toString();
        Map<String, Object> claims = new HashMap<>();
        claims.put("id",id);
        String jwt = JwtUtils.createJWT(claims,10000000L);
        //将完整信息存入redis 其中userId作为key

        User userMap = loginUser.getUser();
        log.info("token:" + jwt);
        redisService.set("login" + loginUser.getUser().getId(),loginUser);

        return new Result(jwt,true,loginUser.getUser().getStatus()==1?"登录成功":"账号已被冻结", 20000);
    }

    public Result register(User user){
        user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
        user.setStatus(1);
        user.setLevel("青铜");
        userService.addOrUpdateUserInfo(user);

        User user1 = userService.getUserInfoByUsername(user.getUsername()); //获取新建用户信息
        Long userId = user1.getId();


        UserRole userRole = new UserRole();  //为新用户创建对应角色id
        userRole.setRoleId(4L);
        userRole.setUserId(userId);
        userRoleMapper.insert(userRole);

        Balance balance = new Balance(); //为新用户创建余额信息
        balance.setBalance(new BigDecimal(0));
        balance.setPoints(new BigDecimal(0));
        balance.setUsername(user1.getUsername());
        balance.setUserId(userId);
        balanceMapper.insert(balance);

        return new Result(ResultStatus.REGISTER_SUCCESS.getMsg(),ResultStatus.REGISTER_SUCCESS.getCode());
    }
}
